{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: High resolution static solves\n", "\n", "---\n", "\n", "This notebook showcases how to leverage several optional features of FreeGSNKE when carrying out static equilibrium solves on much larger computational grids (i.e. when high resolution is required).\n", "\n", "The resolution of the grid is generally limited by two factors: \n", "1. the amount of memory demanded from the system (usually a hard limit). \n", "2. the execution time required for the calculation to compute (soft limit). \n", "\n", "In the following, we will go through some of the following features that can address these issues, with some considerations the user may want to take into account before using them:\n", "\n", "- *Multithreading* in critical computations\n", " - Can substantially **reduce execution time** in static solves\n", " - May **hamper performance** if used on **small grids**\n", " - On **personal computers** performance **may vary drastically** due to other running processes\n", "- *On-the-fly computation* of the boundary Green's function\n", " - Significantly **reduces memory** required, allowing to run larger systems\n", " - Noticeably **increases execution time** due to recalculation\n", " - Reduction in memory use **can be tuned**\n", " - Strongly **discouraged** for evolutive solves (see later examples)\n", "- Use of frequency-based DST solver\n", " - **Faster** than the default sparse LU solver\n", " - Uses **less memory** than the default sparse solver\n", " - Is **less accurate** ($O(\\delta^2)$) than the default ($O(\\delta^4)$)" ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### Import packages" ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import pickle\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from time import perf_counter" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "### Initialise the openSTEP machine\n", "\n", "First, let's initialise the openSTEP machine geometry (as in example07h)." ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "from freegsnke import build_machine\n", "\n", "# build the machine\n", "tokamak = build_machine.tokamak(\n", " active_coils_path=f\"../machine_configs/OpenSTEP/OpenSTEP_simple_active_coils.pickle\",\n", " limiter_path=f\"../machine_configs/OpenSTEP/OpenSTEP_simple_limiter.pickle\",\n", " wall_path=f\"../machine_configs/OpenSTEP/OpenSTEP_simple_limiter.pickle\",\n", ")\n", "\n", "# plot the machine\n", "fig1, ax1 = plt.subplots(1, 1, figsize=(3, 8), dpi=80)\n", "ax1.grid(zorder=0, alpha=0.75)\n", "ax1.set_aspect('equal')\n", "tokamak.plot(axis=ax1,show=False)\n", "ax1.fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0) \n", "ax1.set_xlabel(\"Major radius [m]\")\n", "ax1.set_ylabel(\"Height [m]\")\n", "plt.show()\n", "\n" ] }, { "cell_type": "markdown", "id": "5", "metadata": {}, "source": [ "### Initialise profiles and eq objects\n", "\n", "Let's start by initialising the usual objects on a \"small\" computational grid - later we will show this is not enough to resolve the STEP equilibrium with its complex internal $p'$ and $FF'$ profiles." ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": {}, "outputs": [], "source": [ "# load the p' and FF' profile data from file\n", "with open('../machine_configs/OpenSTEP/OpenSTEP_profiles.pickle', 'rb') as f:\n", " profiles_data = pickle.load(f)" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "from freegsnke import equilibrium_update\n", "from freegsnke.jtor_update import GeneralPprimeFFprime\n", "from freegsnke.equilibrium import PsiGuessParabolicJtor\n", "\n", "# reference coil currents\n", "currents = np.array([\n", " -4790870.39240653,\n", " 5155466.64491291,\n", " 2254704.04332795,\n", " 5458947.31403196,\n", " -7854367.88994826,\n", " 5100000.0,\n", " -2274646.53005716,\n", "])\n", "\n", "# initial plasma flux guess factory\n", "parabolic_plasma_psi = PsiGuessParabolicJtor(\n", " Ip=2.2767e7, # plasma current (to scale the guess)\n", " h=4.0, # centre of ellipse (R)\n", " k=0.0, # centre of ellipse (Z)\n", " a=1.0, # approximate minor radius of the plasma\n", " b=5.0, # approximate minor radius times elongation\n", " psi_scale=1.0,\n", ")\n", "\n", "# function for building the eq and profiles repeatedly\n", "def setup_openstep(nx: int, ny: int):\n", " \"\"\"Build an OpenSTEP Equilibrium and GeneralPprimeFFprime profile on an (nx, ny) grid.\"\"\"\n", " eq = equilibrium_update.Equilibrium(\n", " tokamak=tokamak,\n", " Rmin=0.5,\n", " Rmax=9.0,\n", " Zmin=-10.0,\n", " Zmax=10.0,\n", " nx=nx, # must be of the form 2**n + 1\n", " ny=ny, # must be of the form 2**n + 1\n", " )\n", " profiles = GeneralPprimeFFprime(\n", " eq=eq,\n", " Ip=2.2767e7,\n", " fvac=0.5,\n", " psi_n=np.linspace(0, 1, 256),\n", " pprime_data=profiles_data['pprime'],\n", " ffprime_data=profiles_data['ffprime'],\n", " )\n", " eq.tokamak.set_all_coil_currents(currents)\n", " eq.plasma_psi = parabolic_plasma_psi(eq=eq)\n", " return eq, profiles\n", "\n", "# initialise and build the plasma flux guess\n", "eq, profiles = setup_openstep(nx=65, ny=129)\n", "_plasma_psi = eq.plasma_psi.copy()" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "### Solve equilibrium using defaults\n", "\n", "We'll first solve for the equilibrium using all of the default solver settings for comparison later on." ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "from freegsnke import GSstaticsolver\n", "\n", "GSStaticSolver = GSstaticsolver.NKGSsolver(\n", " eq=eq,\n", " solver_type=\"LUsparse\",\n", " gs_operator_order=4,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "# solve\n", "GSStaticSolver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-10,\n", " force_up_down_symmetric=True,\n", " verbose=False,\n", ")" ] }, { "cell_type": "markdown", "id": "11", "metadata": {}, "source": [ "### Store results and plot" ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "# some array to store results\n", "resolutions = []\n", "psi_results = []\n", "x_points = []\n", "o_points = []\n", "jtor_results = []\n", "\n", "# save the results\n", "resolutions.append((eq.nx,eq.ny))\n", "psi_results.append(eq.psi())\n", "x_points.append(profiles.xpt)\n", "o_points.append(profiles.opt)\n", "jtor_results.append(profiles.jtor)\n", "\n", "# plot initial plasma flux guess\n", "fig0, (ax01,ax02) = plt.subplots(1, 2, figsize=(8, 8), dpi=80)\n", "ax01.grid(zorder=0, alpha=0.75)\n", "ax01.set_aspect('equal')\n", "eq.tokamak.plot(axis=ax01,show=False)\n", "ax01.plot(tokamak.wall.R, tokamak.wall.Z, 'k')\n", "ax01.contour(eq.R, eq.Z, _plasma_psi)\n", "ax01.set_title(\"Initial plasma flux guess\")\n", "\n", "# plot the equilibrium\n", "plt.ion()\n", "ax02.grid(zorder=0, alpha=0.75)\n", "ax02.set_aspect('equal')\n", "eq.tokamak.plot(axis=ax02,show=False) # plots the active coils and passive structures\n", "ax02.fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0) # plots the limiter\n", "eq.plot(axis=ax02,show=False)\n", "ax02.set_title(\"Final (total) poloidal flux\")\n", "plt.tight_layout()\n", "# plt.legend()" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "### Benchmark 1: Setting the number of threads\n", "\n", "We can use **multithreading** to solve on much larger grids. \n", "\n", "This is useful when creating `Equilibrium`, `NKGSsolver`, or calling `solve()` with larger grids. " ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "\n", "### 1. Default settings\n", "When you import freegsnke, the defaults are:\n", "- **FreeGSNKE's internal parallel loops:** `1` thread (serial).\n", "- **NumPy / SciPy (linear algebra):** uses your system's OpenMP/BLAS default (typically all available CPU cores, unless `OMP_NUM_THREADS` is set)." ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "# first inspect the current settings\n", "from freegsnke import parallel\n", "\n", "print(\"Current freegsnke threads:\", parallel.get_num_threads())" ] }, { "cell_type": "markdown", "id": "16", "metadata": {}, "source": [ "### 2. How to change them\n", "\n", "**Option A** — Inside your Python script or notebook (most common):\n", "\n", "Call `parallel.set_num_threads(n)` **before** creating `Equilibrium`, `NKGSsolver`, or calling `solve()`:\n", "```python\n", "from freegsnke import parallel\n", "parallel.set_num_threads(4) # use 4 threads for FreeGSNKE\n", "```\n", "\n", "(Alternatively, call `parallel.set_max_threads()` to set the maximum number of threads based on FreeGSNKE's assessment of the physical resources available)\n", "\n" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "**Option B** — Before starting Python (for terminal / HPC runs):\n", "\n", "Set `OMP_NUM_THREADS` before launching Python or Jupyter to control **both** FreeGSNKE and NumPy/SciPy together:\n", "```bash\n", "OMP_NUM_THREADS=4 python my_script.py\n", "```" ] }, { "cell_type": "markdown", "id": "18", "metadata": {}, "source": [ "### 3. When should you change them?\n", "\n", "| Situation | What to do | Why |\n", "| :--- | :--- | :--- |\n", "| **Normal / small grids** (e.g. `65x65`, `65x129`) | **Do nothing** (leave at `1`). | Starting extra threads adds overhead; on small grids, `1` thread is often faster. |\n", "| **Large grids on a laptop/workstation** (e.g. `257x513` or `cache_greens=False`) | Call `parallel.set_num_threads(n)` with `n` up to your **physical CPU core count** (e.g. `4` or `8`). | The grid calculations are large enough that multiple threads give a real speedup. |\n", "| **Running on an HPC cluster (e.g. SLURM)** | Set `OMP_NUM_THREADS=` before launching Python. | Prevents NumPy/SciPy and FreeGSNKE from trying to use more CPUs than your job was allocated. |" ] }, { "cell_type": "markdown", "id": "19", "metadata": {}, "source": [ "In this experiment, we benchmark `nt = [1, 2, 4, 8]` threads on two grid resolutions (`65x129` and `129x257`) across three linear GS solver configurations: `LUsparse` (2nd order), `LUsparse` (4th order), and `DST` (2nd order).\n", "\n", "> **Warning:** The following cell is intentionally computationally expensive and may take several minutes to complete." ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "from freegsnke.parallel import set_num_threads\n", "\n", "grids = [(65, 129), (129, 257)]\n", "num_threads = [1, 2, 4, 8]\n", "solvers = [\n", " ('LUsparse (2nd order)', 'LUsparse', 2),\n", " ('LUsparse (4th order)', 'LUsparse', 4),\n", " ('DST (2nd order)', 'DST', 2),\n", "]\n", "\n", "# store solver times: solve_times[(nx, ny)][label] = [t_nt1, t_nt2, ...]\n", "solve_times = {grid: {label: [] for label, _, _ in solvers} for grid in grids}\n", "\n", "for nx, ny in grids:\n", " print(f'=== Grid {nx}x{ny} ===')\n", " for label, solver_type, order in solvers:\n", " for nt in num_threads:\n", " # use 2 threads for equilibrium & coil Green's initialisation\n", " set_num_threads(2)\n", " eq, profiles = setup_openstep(nx=nx, ny=ny)\n", "\n", " # set requested thread count for solver initialisation and solve\n", " set_num_threads(nt)\n", " t1 = perf_counter()\n", " GSStaticSolver = GSstaticsolver.NKGSsolver(\n", " eq=eq,\n", " solver_type=solver_type,\n", " gs_operator_order=order,\n", " cache_greens=True,\n", " )\n", " GSStaticSolver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-6,\n", " force_up_down_symmetric=True,\n", " verbose=False,\n", " )\n", " elapsed = perf_counter() - t1\n", " solve_times[(nx, ny)][label].append(elapsed)\n", " print(f' {label:22s} | nt={nt} | {elapsed:.2f}s')\n", "\n", " if (nx, ny) == (129, 257) and label == 'LUsparse (4th order)' and nt == num_threads[-1]:\n", " resolutions.append((eq.nx, eq.ny))\n", " psi_results.append(eq.psi())\n", " x_points.append(profiles.xpt)\n", " o_points.append(profiles.opt)\n", " jtor_results.append(GSStaticSolver.jtor)\n", "\n", "# reset to default thread count\n", "set_num_threads(1)" ] }, { "cell_type": "code", "execution_count": null, "id": "21", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, len(grids), figsize=(10, 4), dpi=100, sharey=False)\n", "\n", "for ax, (nx, ny) in zip(axes, grids):\n", " for label, _, _ in solvers:\n", " ax.plot(num_threads, solve_times[(nx, ny)][label], marker='o', label=label)\n", " ax.set_title(f'Grid {nx}x{ny}')\n", " ax.set_xlabel('Number of threads (set_num_threads)')\n", " ax.set_ylabel('Solver init + solve time [s]')\n", " ax.set_xticks(num_threads)\n", " ax.grid(alpha=0.4)\n", " ax.legend()\n", "\n", "plt.tight_layout()" ] }, { "cell_type": "markdown", "id": "22", "metadata": {}, "source": [ "The results show:\n", "- **Small grid (`65x129`):** `nt=1` is fastest (`~0.7–1.0s`). Increasing `nt` slightly slows the solve (`~0.8–1.2s`) because thread-management overhead outweighs the parallel work on small arrays.\n", "- **Larger grid (`129x257`):** Multithreading speeds up all three solvers when moving from `nt=1` to `nt=4`–`8` (roughly a `25–30%` reduction in runtime), with diminishing returns beyond `nt=4` as serial work and physical core count limit scaling.\n", "- **Solver comparison:** `DST (2nd order)` is faster than `LUsparse (4th order)` on the `129x257` grid and matches `LUsparse (2nd order)` iteration-for-iteration (`23` iterations).\n", "- **Determinism:** For each solver and grid, the iteration count and final relative error are identical across all `nt` values.\n", "\n", "It should be noted that the number of iterations above is consistent between runs: FreeGSNKE's implementation of threading for static solves is *fully deterministic*: numerical results are exactly replicated independently of the number of threads. \n", "\n", "The same is **not true** of the parallel backends used by `numpy`, so results will present differences if parallelism is varied with environment variables, but not if controlled with the `freegsnke.parallel` API." ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "## Benchmark 2: Effect of on-the-fly Green's functions\n", "\n", "By default (`cache_greens=True`), `NKGSsolver` pre-computes and stores the boundary Green's function matrix in RAM. On very fine grids this matrix can exceed available system memory. Setting `cache_greens=False` avoids storing it by recomputing the boundary flux on-the-fly at each iteration—reducing memory usage by up to an order of magnitude at the cost of extra computation (and making multithreading much more impactful). Because of this runtime cost, `cache_greens=False` should be avoided for evolutive solves.\n", "\n", "Next, we repeat the thread sweep (`nt = [1, 2, 4, 8]`) on `65x129` and `129x257` using the `DST` solver with `cache_greens=False`, and compare the runtimes against the `cache_greens=True` results from Benchmark 1." ] }, { "cell_type": "code", "execution_count": null, "id": "24", "metadata": {}, "outputs": [], "source": [ "otf_times = {grid: [] for grid in grids}\n", "\n", "for nx, ny in grids:\n", " print(f\"=== Grid {nx}x{ny} (DST, cache_greens=False) ===\")\n", " for nt in num_threads:\n", " set_num_threads(2)\n", " eq, profiles = setup_openstep(nx=nx, ny=ny)\n", "\n", " set_num_threads(nt)\n", " t1 = perf_counter()\n", " GSStaticSolver = GSstaticsolver.NKGSsolver(\n", " eq=eq,\n", " solver_type=\"DST\",\n", " cache_greens=False,\n", " )\n", " GSStaticSolver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-6,\n", " force_up_down_symmetric=True,\n", " verbose=False,\n", " )\n", " elapsed = perf_counter() - t1\n", " otf_times[(nx, ny)].append(elapsed)\n", " print(f\" nt={nt} | {elapsed:.2f}s\")\n", "\n", "set_num_threads(1)" ] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(2, len(grids), figsize=(10, 7), dpi=100, sharex=True)\n", "\n", "for col, (nx, ny) in enumerate(grids):\n", " t_cached = np.array(solve_times[(nx, ny)][\"DST (2nd order)\"])\n", " t_otf = np.array(otf_times[(nx, ny)])\n", "\n", " # Top row: raw runtime\n", " axes[0, col].plot(num_threads, t_cached, marker=\"o\", label=\"cache_greens=True\")\n", " axes[0, col].plot(num_threads, t_otf, marker=\"s\", label=\"cache_greens=False\")\n", " axes[0, col].set_title(f\"Grid {nx}x{ny} (DST)\")\n", " axes[0, col].set_ylabel(\"Solver init + solve time [s]\")\n", " axes[0, col].grid(alpha=0.4)\n", " axes[0, col].legend()\n", "\n", " # Bottom row: speedup relative to nt=1\n", " axes[1, col].plot(num_threads, t_cached[0] / t_cached, marker=\"o\", label=\"cache_greens=True\")\n", " axes[1, col].plot(num_threads, t_otf[0] / t_otf, marker=\"s\", label=\"cache_greens=False\")\n", " axes[1, col].axhline(1.0, color=\"k\", linestyle=\"--\", linewidth=0.8, alpha=0.6)\n", " axes[1, col].set_xlabel(\"Number of threads (set_num_threads)\")\n", " axes[1, col].set_ylabel(\"Speedup vs nt=1\")\n", " axes[1, col].set_xticks(num_threads)\n", " axes[1, col].grid(alpha=0.4)\n", " axes[1, col].legend()\n", "\n", "plt.tight_layout()" ] }, { "cell_type": "markdown", "id": "26", "metadata": {}, "source": [ "Initially it appears as if setting `cache_greens=False` is always a bad option but this is not the case:\n", "\n", "- **Memory-vs-runtime trade-off:** `cache_greens=True` is always faster and should be used whenever the boundary Green's matrix fits in RAM. Setting `cache_greens=False` is strictly a workaround for large grids that would otherwise exceed available memory.\n", "- **Stronger thread scaling:** Although `cache_greens=False` has a higher total runtime, recomputing the boundary flux on-the-fly is heavily parallelisable, so its relative speedup with `set_num_threads` (bottom row) is much steeper than with `cache_greens=True`.\n", "\n", "Additionally, `cache_greens=False` should be **avoided completely** when the intention is to perform an evolutive solve: in this case, the performance cost will become prohibitively expensive and the memory savings will be less significant. There are other tools for reducing memory use in evolutive solves, some of which are explained in **example 05a**." ] }, { "cell_type": "markdown", "id": "27", "metadata": {}, "source": [ "The flag `max_batch_size` can also be used when initialising the solver object to allow for a further decrease in memory, by reducing the size of the portion of the Green's function that can be held in memory at a time. \n", "\n", "Its main intended use is for very resolved grids on HPC systems — here, the default is `2_000_000_000` maximum batch size which puts an upper ceiling of ~64GB on the memory. This value can be reduced if needed to fit the computer you are using.\n", "\n", "Finally, let's try an even larger solve using all of the above functionality — checking how much memory it would have required vs. without." ] }, { "cell_type": "code", "execution_count": null, "id": "28", "metadata": {}, "outputs": [], "source": [ "# higher-resolution solve without caching the full boundary Green's matrix (you can go higher if you wish!)\n", "nx = 257\n", "ny = 513\n", "max_batch_size = 100_000_000 # set ~3.2 GB max per temporary batch (float64)\n", "\n", "# print memory that has been saved\n", "n_bndry = 2 * (nx + ny) - 4\n", "full_greens_gb = n_bndry * nx * ny * 8 / 1e9\n", "batch_gb = max_batch_size * 8 / 1e9\n", "print(f\"Grid {nx}x{ny}: full cached greenfunc would require {full_greens_gb:.2f} GB \"\n", " f\"(batch limit set to {batch_gb:.2f} GB)\")\n", "\n", "# monitor performance (setting up machine)\n", "t0 = perf_counter()\n", "set_num_threads(4)\n", "eq, profiles = setup_openstep(nx=nx, ny=ny)\n", "t1 = perf_counter()\n", "print(f\"Equilibrium and profiles built in {t1 - t0:.2f}s\", flush=True)\n", "\n", "# monitor peformance (initialising + solving equilibrium)\n", "GSStaticSolver = GSstaticsolver.NKGSsolver(\n", " eq=eq,\n", " solver_type=\"LUsparse\",\n", " gs_operator_order=4,\n", " cache_greens=False,\n", " max_batch_size=max_batch_size,\n", ")\n", "\n", "GSStaticSolver.solve(\n", " eq=eq,\n", " profiles=profiles,\n", " target_relative_tolerance=1e-6,\n", " force_up_down_symmetric=True,\n", " verbose=True,\n", ")\n", "t2 = perf_counter()\n", "print(f\"Equilibrium solved in {t2 - t1:.2f}s (total {t2 - t0:.2f}s)\")\n", "\n", "# reset thread count and store results for the resolution comparison below\n", "set_num_threads(1)\n", "resolutions.append((nx, ny))\n", "psi_results.append(eq.psi())\n", "x_points.append(profiles.xpt)\n", "o_points.append(profiles.opt)\n", "jtor_results.append(GSStaticSolver.jtor)" ] }, { "cell_type": "markdown", "id": "29", "metadata": {}, "source": [ "### Comparison of the equilibria\n", "\n", "At this point we have saved results for 3 different grid resolutions (all `LUsparse` 4th order results), so we can now compare them, in order to see the effect of using more resolved grids." ] }, { "cell_type": "markdown", "id": "30", "metadata": {}, "source": [ "First, let's look at the plasma equilibrium - you can see some slight changes in the plasma shape and boundary with increasing resolution." ] }, { "cell_type": "code", "execution_count": null, "id": "31", "metadata": {}, "outputs": [], "source": [ "# plot\n", "num_figs = len(resolutions)+1\n", "fig1, axes = plt.subplots(1, num_figs, figsize=(3.5*num_figs*1.2, 7), dpi=80)\n", "\n", "# plot initial guess\n", "ax0 = axes[0]\n", "ax0.grid(zorder=0, alpha=0.75)\n", "ax0.set_aspect('equal')\n", "eq.tokamak.plot(axis=ax0,show=False)\n", "ax0.plot(tokamak.wall.R, tokamak.wall.Z, 'k')\n", "R, Z = np.meshgrid(\n", " np.linspace(eq.Rmin,eq.Rmax,_plasma_psi.shape[0]),\n", " np.linspace(eq.Zmin,eq.Zmax,_plasma_psi.shape[1]),\n", " indexing=\"ij\"\n", ")\n", "ax0.contour(R, Z, _plasma_psi)\n", "ax0.set_title(\"Initial plasma flux guess\")\n", "\n", "for i in range(len(resolutions)):\n", "\n", " nr,nz = resolutions[i]\n", " axes[i+1].set_title(f\"Total flux (${nr}\\\\times{nz}$)\")\n", " axes[i+1].grid(zorder=0, alpha=0.75)\n", " axes[i+1].set_aspect('equal')\n", " eq.tokamak.plot(axis=axes[i+1],show=False) # plots the active coils and passive structures\n", " axes[i+1].fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0) # plots the limiter\n", " R, Z = np.meshgrid(\n", " np.linspace(eq.Rmin,eq.Rmax,nr),\n", " np.linspace(eq.Zmin,eq.Zmax,nz),\n", " indexing=\"ij\"\n", " )\n", " axes[i+1].contour(R, Z, psi_results[i],levels=np.linspace(np.amin(psi_results[i]), np.amax(psi_results[i]), 35))\n", "\n", " \n", " axes[i+1].contour(R,Z,psi_results[i],levels=[x_points[i][0][2]],colors='r')\n", " for r, z, _ in x_points[i]:\n", " axes[i+1].plot(r, z, \"rx\", markersize=9)\n", " axes[i+1].plot(x_points[i][0][0], x_points[i][0][1], \"rx\", markersize=9, markeredgewidth=2.5)\n", " for r, z, _ in o_points[i]:\n", " axes[i+1].plot(r, z, \"g2\", markersize=9)\n", "\n", " axes[i+1].set_yticklabels([])\n", " axes[i+1].set_ylabel(\"\")\n", "\n" ] }, { "cell_type": "markdown", "id": "32", "metadata": {}, "source": [ "This can be seen further if we plot jtor at a few different $Z$ levels.\n", "\n", "The results show that the bootstrap current at the plasma edge is still not fully resolved - in addition to the outboard midplane boundary!\n", "\n", "This highlights the importance of fully resolving complex equilibria! In this particular case, it looks like we would need even more resolution at the edge!" ] }, { "cell_type": "code", "execution_count": null, "id": "33", "metadata": {}, "outputs": [], "source": [ "def extract_jtor(jtor,z_vals):\n", " midline = jtor.shape[-1]//2\n", " return tuple(jtor[:,midline + int(z_val/20.*jtor.shape[-1])] for z_val in z_vals)\n", "\n", "\n", "num_figs = len(resolutions)\n", "fig2, axes2 = plt.subplots(1, num_figs, figsize=(3.5*num_figs*1.2, 7), dpi=80)\n", "max_jtor = max([jtor.max() for jtor in jtor_results])\n", "\n", "for i in range(len(resolutions)):\n", "\n", " nr,nz = resolutions[i]\n", " axes2[i].set_title(f\"${nr}\\\\times{nz}$\")\n", " img = axes2[i].imshow(jtor_results[i].T,vmin=0,vmax=max_jtor,extent=(0.5,9.,-10,10),cmap='inferno')\n", " axes2[i].fill(tokamak.wall.R, tokamak.wall.Z, color='b', linewidth=1.2, facecolor=('w',0), zorder=0) # plots the limiter\n", " axes2[i].grid(zorder=0, alpha=0.75)\n", " eq.tokamak.plot(axis=axes2[i],show=False) # plots the active coils and passive structures\n", " if i!=0:\n", " axes2[i].set_yticklabels([])\n", " axes2[i].set_ylabel(\"\")\n", " img0 = img\n", "\n", "fig2.colorbar(img0,ax=axes2,orientation=\"vertical\",fraction=0.1)\n", "\n", "z_vals = [6,5,4,0]\n", "num_figs = len(z_vals)\n", "fig1, axes = plt.subplots(num_figs, 1, figsize=(12, 3*num_figs), dpi=80)\n", "\n", "for jtor_field,(nr,nz) in zip(jtor_results,resolutions):\n", " jtor_curves = extract_jtor(jtor_field,z_vals)\n", " n_curves = len(jtor_curves)\n", " for i in range(n_curves):\n", " jtor = jtor_curves[i]\n", " axes[i].plot(np.linspace(0.5,9.,len(jtor)),jtor,label=f\"${nr}\\\\times{nz}$\")\n", " axes[i].set_ylim(0,max(1e6,jtor.max()*1.05))\n", "\n", "for i in range(num_figs):\n", " axes[i].set_ylabel(f\"$z={z_vals[i]}$\")\n", " axes[i].grid()\n", " axes[i].set_xlim(1.0,6.5)\n", "\n", "axes[0].legend(title='Resolution')\n", "axes[num_figs//2].set_ylabel(\"Jtor\\n\"+axes[num_figs//2].get_ylabel())\n", "axes[-1].set_xlabel(\"Major radius [m]\")\n", "plt.show()\n" ] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }